package com.aiyige.page.coupon;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.service.ApiService;
import com.aiyige.model.Page;
import com.aiyige.model.User;
import com.aiyige.page.coupon.adapter.UserCouponAdapter;
import com.aiyige.page.coupon.model.DrawCouponWithExchangeCodeRequest;
import com.aiyige.page.coupon.model.DrawCouponWithExchangeCodeResponse;
import com.aiyige.page.coupon.model.UserCoupon;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.SafeAsyncTask;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UIHelper;
import com.aiyige.utils.widget.AutoRefreshCommonDataView;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.loadmore.LoadMoreView;

import org.w3c.dom.Text;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

@Route(path = ARouterConfig.UserCouponPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class UserCouponPage extends AppCompatActivity implements CommonDataView.RetrofitStub {
    public static final int REQUEST_CODE_DRAW_COUPON_PAGE = 123;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    TextView titleActionBtn;
    @BindView(R.id.cdv)
    AutoRefreshCommonDataView cdv;
    @BindView(R.id.codeEt)
    EditText codeEt;
    UserCouponAdapter adapter;
    volatile boolean shouldRefresh = false;
    View emptyView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_user_coupon);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        emptyView = LayoutInflater.from(this).inflate(R.layout.user_coupon_empty_layout, cdv.getRecyclerView(), false);
        emptyView.findViewById(R.id.viewHistoryCouponLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance()
                        .build(ARouterConfig.HistoryCouponPage)
                        .navigation(UserCouponPage.this);
            }
        });
        cdv.setEmptyView(emptyView);
        titleTv.setText(R.string.coupon);
        titleActionBtn.setText(R.string.draw_coupon_center);
        adapter = new UserCouponAdapter();
        cdv.setLoadMoreView(new LoadMoreView() {
            View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ARouter.getInstance()
                            .build(ARouterConfig.HistoryCouponPage)
                            .navigation(UserCouponPage.this);
                }
            };

            @Override
            public void convert(BaseViewHolder holder) {
                super.convert(holder);
                View v = holder.getView(R.id.viewHistoryCouponLayout);
                v.setOnClickListener(onClickListener);
            }

            @Override
            public int getLayoutId() {
                return R.layout.user_coupon_load_more_view;
            }

            @Override
            protected int getLoadingViewId() {
                return R.id.load_more_loading_view;
            }

            @Override
            protected int getLoadFailViewId() {
                return R.id.load_more_load_fail_view;
            }

            @Override
            protected int getLoadEndViewId() {
                return R.id.load_more_load_end_view;
            }
        });
        cdv.getRecyclerView().setItemAnimator(null);
        cdv.getRecyclerView().addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildAdapterPosition(view);
                if (index == 0) {
                    outRect.set(UIHelper.dip2px(15), UIHelper.dip2px(10), UIHelper.dip2px(15), 0);
                } else {
                    outRect.set(UIHelper.dip2px(15), UIHelper.dip2px(15), UIHelper.dip2px(15), 0);
                }
            }
        });
        cdv.config(adapter, this);
        cdv.setCallback(new AutoRefreshCommonDataView.Callback() {
            @Override
            public void onClearRequestState() {
                if (shouldRefresh) {
                    cdv.doRefreshRequest();
                }
            }
        });
        cdv.doRefreshRequest();
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter a, View view, int position) {
                switch (view.getId()) {
                    case R.id.actionBtn:
                        ARouter.getInstance()
                                .build(ARouterConfig.CouponFilterPage)
                                .withParcelable("userCoupon", adapter.getItem(position))
                                .navigation(UserCouponPage.this);
                        break;
                }
            }
        });
    }

    @OnClick({R.id.exchangeBtn, R.id.titleBackBtn, R.id.titleActionBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                ARouter.getInstance()
                        .build(ARouterConfig.DrawCouponPage)
                        .navigation(this, REQUEST_CODE_DRAW_COUPON_PAGE);
                break;
            case R.id.exchangeBtn:
                doExchangeUserCoupon(codeEt.getText().toString().trim());
                break;
        }
    }

    public void doExchangeUserCoupon(String code) {
        if (TextUtils.isEmpty(code)) {
            ToastX.show(R.string.invalid_exchange_code);
            return;
        }
        new ExchangeUserCouponTask(this, code).execute();
    }

    public class ExchangeUserCouponTask extends SafeAsyncTask<Object, Object, Object> {
        String code;

        public ExchangeUserCouponTask(Activity activity, String code) {
            super(activity, R.string.loading);
            this.code = code;
        }

        @Override
        public void safeOnPostExecute(Object o) {
            if (o instanceof Exception) {
                ToastX.show((Exception) o);
            } else {
                ToastX.show(R.string.exchange_coupon_success);
                codeEt.setText("");
                shouldRefresh = true;
                cdv.refresh();
            }
        }

        @Override
        protected Object doInBackground(Object... objects) {
            try {
                Response<ResponseBody> response = ApiManager.getService().drawCouponWithExchangeCode(DrawCouponWithExchangeCodeRequest.newBuilder().exchangeCode(code).build()).execute();
                if (response.code() != ResponseCode.CREATED) {
                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                }
                return null;
            } catch (Exception e) {
                return e;
            }
        }
    }


    @Override
    public Call<ResponseBody> call(long currentPage) {
        shouldRefresh = false;
        return ApiManager.getService().userCoupon(currentPage, 20);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<UserCoupon> userCouponList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                userCouponList.addAll(JSON.parseArray(page.getContent(), UserCoupon.class));
            }
            for (UserCoupon item : userCouponList) {
                if (item == null) continue;
                UserCoupon safeItem = new UserCoupon(item);
                resultList.add(safeItem);
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_DRAW_COUPON_PAGE:
                cdv.refresh();
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }

    }
}
